package purchase

import (
	"github.com/shopspring/decimal"
)

func (purchaseDetailItem *PurchaseDetailItem) CreatePurchaseDetailItem() error {
	// 采购明细存放到库中
	err := purchaseDetailItem.createPurchaseDetailItem()
	if err != nil {
		return err
	}
	// 依据该采购明细进行更新采购单信息
	purchaseInfo, err := GetPurchaseInfo(purchaseDetailItem.PurchaseID)
	if err != nil {
		return err
	}
	var (
		totalWeight       = decimal.NewFromFloat(0) // 总斤数
		actualTotalAmount = decimal.NewFromFloat(0) // 实际总金额
		autoTotalPrice    = decimal.NewFromFloat(0) // 自动总价
		costUnitPrice     = decimal.NewFromFloat(0) // 成本单价
		settledAmount     = decimal.NewFromFloat(0) // 已结算金额
		remainingAmount   = decimal.NewFromFloat(0) // 剩余结算金额
	)
	for _, item := range purchaseInfo.Items {
		totalWeight = totalWeight.Add(item.Quantity)                 // 叠加计算总斤数
		actualTotalAmount = actualTotalAmount.Add(item.ActualAmount) // 叠加计算实际总金额
		autoTotalPrice = autoTotalPrice.Add(item.TotalPrice)         // 叠加计算自动总价
		settledAmount = settledAmount.Add(item.SettlementAmount)     // 叠加计算已结算金额
	}
	// 成本单价=实际总金额/总斤数
	costUnitPrice = actualTotalAmount.Div(totalWeight)
	// 剩余结算金额=实际总金额-已结算金额
	remainingAmount = actualTotalAmount.Sub(settledAmount)
	// 总数量，采购总斤数
	purchaseInfo.PurchaseTotal = totalWeight
	// 实际总金额
	purchaseInfo.PurchaseActualAmount = actualTotalAmount
	// 自动总价
	purchaseInfo.PurchaseTotalPrice = autoTotalPrice
	// 成本单价
	purchaseInfo.PurchaseUnitCost = costUnitPrice
	// 剩余结算金额
	purchaseInfo.RemainSettlementAmount = remainingAmount

	// 更新采购单付款状态，1未付款，2部分付款，3全部付款
	// 判断剩余结算金额是否为0
	if remainingAmount.Cmp(decimal.NewFromFloat(0)) == 0 {
		purchaseInfo.PurchasePaymentStatus = 3
	} else if remainingAmount.Cmp(decimal.NewFromFloat(0)) > 0 && settledAmount.Cmp(decimal.NewFromFloat(0)) > 0 {
		purchaseInfo.PurchasePaymentStatus = 2
	} else {
		purchaseInfo.PurchasePaymentStatus = 1
	}
	// 清空明细，便于更新
	purchaseInfo.Items = nil
	return purchaseInfo.UpdatePurchaseInfo()
}
